﻿var thai_months = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
( function( $ ) {	
//	$(window).load(function() {
//		$(".loader").fadeOut("slow");
//	});
	
	$("a").click(function(){
		loadpage();
	});
	
	$( document ).ready(function() {
		$.ajaxSetup({
			beforeSend: function(){
				$(".loader").show();
			},
			complete: function(){
				$(".loader").fadeOut("slow");
			},
	        error : function(data){
	        	if(data.code === ""){
					window.location = "${pageContext.request.contextPath}";
	        	}
	        	$.alert(data.code, data.msg);
	        }
		});
		
		$('#cssmenu li.has-sub>a').on('click', function(){
			$(this).removeAttr('href');
			var element = $(this).parent('li');
			if (element.hasClass('open')) {
				element.removeClass('open');
				element.find('li').removeClass('open');
				element.find('ul').slideUp();
			}
			else {
				element.addClass('open');
				element.children('ul').slideDown();
				element.siblings('li').children('ul').slideUp();
				element.siblings('li').removeClass('open');
				element.siblings('li').find('li').removeClass('open');
				element.siblings('li').find('ul').slideUp();
			}
		});

		$('#cssmenu>ul>li.has-sub>a').append('<span class="holder"></span>');
		
		$("button").button();
		
	    var dateBefore=null;
		$.datepicker.setDefaults({
			dateFormat: 'dd MM yy',
			showAnim: "slideDown",
			showOn: "button",
			buttonImageOnly: true,
			buttonText: "Select date",
			showButtonPanel: true,
	        dayNamesMin: ['อา', 'จ', 'อ', 'พ', 'พฤ', 'ศ', 'ส'],
			monthNames: thai_months,
			monthNamesShort: thai_months,
			changeMonth: true,
			changeYear: true,
			isBuddhist: true,
			regional: "th",
			minDate: '01 '+thai_months[4]+' 2013',
			beforeShow:function(){    
	            dateBefore=$(this).val(); 
	            var id = $(this);
	            if($(this).val()!=""){  
	                var arrayDate=$(this).val().split(" ");       
	                arrayDate[2]=parseInt(arrayDate[2]) - 543;  
	                $(this).val(arrayDate[0]+" "+arrayDate[1]+" "+arrayDate[2]);  
	                dateBefore = $(this).val();
	            }  
	            setTimeout(function(){
	                $.each($(".ui-datepicker-year option"),function(j,k){  
	                    var textYear=parseInt($(".ui-datepicker-year option").eq(j).val())+543;  
	                    $(".ui-datepicker-year option").eq(j).text(textYear);
	                });
	                if(id.val()!=''){
		                var arrayDate=id.val().split(" ");       
		                arrayDate[2]=parseInt(arrayDate[2]) + 543;  
		                id.val(arrayDate[0]+" "+arrayDate[1]+" "+arrayDate[2]);
	                }
	            },10); 
	        }, 
	        onChangeMonthYear: function(){  
	            setTimeout(function(){  
	                $.each($(".ui-datepicker-year option"),function(j,k){  
	                    var textYear=parseInt($(".ui-datepicker-year option").eq(j).val())+543;  
	                    $(".ui-datepicker-year option").eq(j).text(textYear);  
	                });               
	            },50);        
	        },  
	        onClose:function(){  
	            if($(this).val()!="" && $(this).val()==dateBefore){           
	                var arrayDate=dateBefore.split(" ");  
	                arrayDate[2]=parseInt(arrayDate[2]);  
	                $(this).val(arrayDate[0]+" "+arrayDate[1]+" "+arrayDate[2]);      
	            }
	        },  
	        onSelect: function(dateText, inst){   
	            dateBefore=$(this).val();  
	            var arrayDate=dateText.split(" ");  
	            arrayDate[2]=parseInt(arrayDate[2]) + 543;  
	            $(this).val(arrayDate[0]+" "+arrayDate[1]+" "+arrayDate[2]);  
	        }     
		});
	});
	
	
	$.widget( "custom.combobox", {
		_create: function() {
			this.wrapper = $( "<span>" ).addClass( "custom-combobox" ).insertAfter( this.element );
	
			this.element.hide();
			this._createAutocomplete();
			this._createShowAllButton();
		},

		_createAutocomplete: function() {
			var selected = this.element.children( ":selected" ),
			value = selected.val() ? selected.text() : "";
	
			this.input = $( "<input>" ).appendTo( this.wrapper ).val( value ).attr( "title", "" )
			.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
			.autocomplete({
				delay: 0,
				minLength: 0,
				source: $.proxy( this, "_source" )
			}).tooltip({
				tooltipClass: "ui-state-highlight"
			}).css({"font-size":"14px", "font-weight": "normal", "width": "350px"});
	
			this._on( this.input, {
				autocompleteselect: function( event, ui ) {
					ui.item.option.selected = true;
					this._trigger( "select", event, {
						item: ui.item.option
					});
				},

				autocompletechange: "_removeIfInvalid"
			});
		},

		_createShowAllButton: function() {
			var input = this.input,
			wasOpen = false;
	
			$( "<a>" ).attr( "tabIndex", -1 ).attr( "title", "ทั้งหมด" ).tooltip().appendTo( this.wrapper ).css("height", "25px")
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				}).removeClass( "ui-corner-all" ).addClass( "custom-combobox-toggle ui-corner-right" )
					.mousedown(function() {
						wasOpen = input.autocomplete( "widget" ).is( ":visible" );
					}).click(function() {
						input.focus();
	
						// Close if already visible
						if ( wasOpen ) {
							return;
						}
	
						// Pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
					});
		},

		_source: function( request, response ) {
			var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
			response( this.element.children( "option" ).map(function() {
				var text = $( this ).text();
				if ( this.value && ( !request.term || matcher.test(text) ) )
				return {
					label: text,
					value: text,
					option: this
				};
			}));
		},

		_removeIfInvalid: function( event, ui ) {

			// Selected an item, nothing to do
			if ( ui.item ) {
				return;
			}
	
			// Search for a match (case-insensitive)
			var value = this.input.val(),
			valueLowerCase = value.toLowerCase(),
			valid = false;
			this.element.children( "option" ).each(function() {
				if ( $( this ).text().toLowerCase() === valueLowerCase ) {
					this.selected = valid = true;
				return false;
				}
			});

			// Found a match, nothing to do
			if ( valid ) {
				return;
			}

			// Remove invalid value
			this.input.val( "" ).attr( "title", value + " ไม่พบข้อมูลนี้" ).tooltip( "open" );
			this.element.val( "" );
			this._delay(function() {
			this.input.tooltip( "close" ).attr( "title", "" );
			}, 2500 );
			this.input.data( "ui-autocomplete" ).term = "";
		},

		_destroy: function() {
			this.wrapper.remove();
			this.element.show();
		}
	});
	
	$.widget( "custom.comboBox", {
		_create: function() {
			this.wrapper = $( "<span>" ).addClass( "custom-comboBox" ).insertAfter( this.element );
	
			this.element.hide();
			this._createAutocomplete();
			this._createShowAllButton();
		},

		_createAutocomplete: function() {
			var selected = this.element.children( ":selected" ),
			value = selected.val() ? selected.text() : "";
	
			this.input = $( "<input disabled='disabled'>" ).appendTo( this.wrapper ).val( value ).attr( "title", "" )
			.addClass( "custom-comboBox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
			.autocomplete({
				delay: 0,
				minLength: 0,
				source: $.proxy( this, "_source" )
			}).tooltip({
				tooltipClass: "ui-state-highlight"
			}).css({"font-size":"14px", "font-weight": "normal", "width": "150px"});
	
			this._on( this.input, {
				autocompleteselect: function( event, ui ) {
					ui.item.option.selected = true;
					this._trigger( "select", event, {
						item: ui.item.option
					});
				},

				autocompletechange: "_removeIfInvalid"
			});
		},

		_createShowAllButton: function() {
			var input = this.input,
			wasOpen = false;
	
			$( "<a>" ).attr( "tabIndex", -1 ).attr( "title", "ทั้งหมด" ).tooltip().appendTo( this.wrapper ).css("height", "30px")
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				}).removeClass( "ui-corner-all" ).addClass( "custom-comboBox-toggle ui-corner-right" )
					.mousedown(function() {
						wasOpen = input.autocomplete( "widget" ).is( ":visible" );
					}).click(function() {
						input.focus();
	
						// Close if already visible
						if ( wasOpen ) {
							return;
						}
	
						// Pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
					});
		},

		_source: function( request, response ) {
			var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
			response( this.element.children( "option" ).map(function() {
				var text = $( this ).text();
				if ( this.value && ( !request.term || matcher.test(text) ) )
				return {
					label: text,
					value: text,
					option: this
				};
			}));
		},

		_removeIfInvalid: function( event, ui ) {

			// Selected an item, nothing to do
			if ( ui.item ) {
				return;
			}
	
			// Search for a match (case-insensitive)
			var value = this.input.val(),
			valueLowerCase = value.toLowerCase(),
			valid = false;
			this.element.children( "option" ).each(function() {
				if ( $( this ).text().toLowerCase() === valueLowerCase ) {
					this.selected = valid = true;
				return false;
				}
			});

			// Found a match, nothing to do
			if ( valid ) {
				return;
			}

			// Remove invalid value
			this.input.val( "" ).attr( "title", value + " ไม่พบข้อมูลนี้" ).tooltip( "open" );
			this.element.val( "" );
			this._delay(function() {
			this.input.tooltip( "close" ).attr( "title", "" );
			}, 2500 );
			this.input.data( "ui-autocomplete" ).term = "";
		},

		_destroy: function() {
			this.wrapper.remove();
			this.element.show();
		},
	});
	
} )( jQuery );

var tablesToExcel = (function () {
    var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>'
    , templateend = '</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>'
    , body = '<body>'
    , tablevar = '<table>{table'
    , tablevarend = '}</table>'
    , bodyend = '</body></html>'
    , worksheet = '<x:ExcelWorksheet><x:Name>'
    , worksheetend = '</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>'
    , worksheetvar = '{worksheet'
    , worksheetvarend = '}'
    , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))); }
    , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); }
    , wstemplate = ''
    , tabletemplate = '';

    return function (table, name, filename) {
        var tables = table;

        for (var i = 0; i < tables.length; ++i) {
            wstemplate += worksheet + worksheetvar + i + worksheetvarend + worksheetend;
            tabletemplate += tablevar + i + tablevarend;
        }

        var allTemplate = template + wstemplate + templateend;
        var allWorksheet = body + tabletemplate + bodyend;
        var allOfIt = allTemplate + allWorksheet;

        var ctx = {};
        for (var j = 0; j < tables.length; ++j) {
            ctx['worksheet' + j] = name[j];
        }

        for (var k = 0; k < tables.length; ++k) {
            var exceltable;
            if (!tables[k].nodeType) exceltable = document.getElementById(tables[k]);
            ctx['table' + k] = exceltable.innerHTML;
        }

        window.location.href = uri + base64(format(allOfIt, ctx)) + ";filename=eeee.xls";

    };
})();

function formatDate(date){
	var d = date.getDate() + "";
	var m = thai_months[date.getMonth()];
	var y = date.getFullYear()+543;
	var lenDate = d.length;
	if(lenDate == 1){
		d = "0" + d;
	}
	return d + ' ' + m + ' ' + y;
}

function toDatepickerValue(dateStr){
	var tmps = dateStr.split("/");
	var d = tmps[0];
	var m = thai_months[parseInt(tmps[1])-1];
	var y = parseInt(tmps[2])+543;
	return d + ' ' + m + ' ' + y;
}

function formatStrDate(date){
	var tmps = date.split(" ");
	if(tmps.length < 3){
		return false;
	}
	var m = 0;
	for(var i=0; i < thai_months.length; i++){
		var month = thai_months[i];
		if(tmps[1] === month){
			m = i+1;
			break;
		}
	}
	
	var y = parseInt(tmps[2]) - 543;
	return tmps[0] + "/" + m + "/" + y;
}

function checkDate(fromDate, toDate){
	if(fromDate === "" || toDate === ""){
		return false;
	}
	var tmpsFromDate = fromDate.split("/");
	var tmpsToDate = toDate.split("/");
	
	var fDate = new Date(parseInt(tmpsFromDate[2]), parseInt(tmpsFromDate[1]) - 1, tmpsFromDate[0]);
	var tDate = new Date(parseInt(tmpsToDate[2]), parseInt(tmpsToDate[1]) - 1, tmpsToDate[0]);
	if(fDate > tDate){
		$.alert('', "โปรดระบุ จากวันที่ ให้น้อยกว่าหรือเท่ากับ ถึงวันที่");
		return false;
	}
	return true;
}

function currencyFormat(num) {
	var tmp = "" + num;
	if(num === null){
		num = 0;		
	}
	if(num===0){
		tmp = num + ".00000";
	}
	var index = tmp.indexOf(".");
	var amount = tmp.substring(0, index);
	var currency = tmp.substring(index, tmp.length);
	
	var curLength = currency.length;
	if(curLength === 5){
		currency = currency + "0";
	}else if(curLength === 4){
		currency = currency + "00";
	}else if(curLength === 3){
		currency = currency + "000";
	}else if(curLength === 2){
		currency = currency + "0000";
	}
	
	currency = currency.substring(0, 6);
	
	var val = parseFloat(amount + currency).toFixed(5).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
	index = val.indexOf(".");
	total = val.substring(0, index);
	currency = val.substring(index, val.length);
	currency = currency.replace(",", "");
    return total + currency;
	//return.toFixed(5).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

function loadpage(){
	$(".loader").show();
}

function fnExcelReport(tableId, xlsName){
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById(tableId); // id of table
    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,xlsName+".xls");
    }else{                 //other browser not tested on IE 11
        //sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
        var a = document.createElement('a');
        //getting data from our div that contains the HTML table
        var data_type = 'data:application/vnd.ms-excel';
        var table_div = document.getElementById(tableId);
        var table_html = table_div.outerHTML.replace(/ /g, '%20');
        //a.href = data_type + ', ' + window.btoa(unescape(encodeURIComponent(table_html)));
        a.href = data_type + ', ' + table_html;
        //setting the file name
        a.download = xlsName+'.xls';
        //triggering the function
        //window.location.href=data_type + ', ' + window.btoa(unescape(encodeURIComponent(table_html)));
        a.click();
        //just in case, prevent default behaviour
        //e.preventDefault();
    }  

    //return (sa);
}

function validateNumuric(value){
	var numuric_regex = "/^[0-9]+$/";
	//return value.test(numuric_regex);
	return !isNaN(value);
}

function currency2Digit(num){
	if(num === null || num === ''){
		num = 0;
	}
	return parseFloat(num).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

function nullToEmpty(value){
	return value === null ? '' : value;
}

function toMoneyFormat(value){
	return value.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}